package org.example.spring.repository.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;
import org.example.spring.repository.service.IDepartmentService;
import org.example.spring.repository.service.IManyThreadsTransactionService;
import org.example.spring.utils.TransactionUtil;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.*;

/**
 * LuoYu
 * 2022/12/14 17:35
 **/
@Service
@Slf4j
@Primary
public class ManyThreadsTransactionServiceImpl implements IManyThreadsTransactionService {

    private static final ExecutorService executor = Executors.newFixedThreadPool(4);

    @Resource
    private IDepartmentService departmentService;

    @Override
    public void exec() {

        // 开启事务
        TransactionStatus transactionStatus = TransactionUtil.getTransactionStatus();
        int size = 10;
        List<Future<Boolean>> list = Lists.newArrayList();
        for (int i = 0; i < size; i++) {
            String string = String.valueOf(i);
            Future<Boolean> future = executor.submit(() -> {
                boolean b = departmentService.create(string, false);
                return b;
            });
            list.add(future);
        }
        try {
            boolean hasRoom = false;
            // 执行完成
            for (Future<Boolean> future : list) {
                try {
                   boolean  aBoolean = future.get();
                    if(!aBoolean) {
                        // 执行回滚
                        hasRoom = true;
                    }
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            if(hasRoom) {
                log.info("执行回滚");
                TransactionUtil.getTransactionManager().rollback(transactionStatus);

            } else {
                log.info("执行提交");
                TransactionUtil.getTransactionManager().commit(transactionStatus);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }




















}
